const shell = require('shelljs');
const inquirer = require('inquirer');
const prompsConfig = require('./config/promps');
const chalk = require('chalk');



async function checkES(str = 'npm run lint:es') {
    let code = 0;
    try {
        code = await shell.exec(str).code
    } catch (err) {
        shell.exec('echo exit 1')
    }
    return code
}

const transformer = async () => {
    let message;
    try{
        let prompt = await inquirer.createPromptModule();
        message = await prompt({
            type: 'input',
            name: 'commit',
            message: 'commit的内容:'
        })
    }catch(err){
        shell.exec('echo exit 1')
    } finally {
        return message
    }
}

const gitPush = async (message) => {
    if(!shell.which('git')){
        shell.echo('Sorry, this script requires git'); 
        shell.exit(1);
    }

    let canPull = shell.error('git pull');
    if(!canPull){
        shell.exec(
            `git add . && git commit -m "${message}" && git push`,
            function () {
                console.log(
                    chalk.cyan(
                        `\n提交脚本: git add . && git commit -m "${message}" && git push`
                    )
                );
            }
        );
    }
}

const log = (msg, color = 'blue') => {
    console.log(
        chalk[color](msg)
    );
}


const init = async () => {
    log('---------start---------')
    let code = await checkES()
    if (code !== 0) {
        log('eslint lint 未通过', 'red');
        let lint = await inquirer.prompt(prompsConfig.lint);
        if (lint.isFix === 'true') {
            log('选择自动修复');
            let code = await checkES('npm run lint:es_fix')
            if (code !== 0) {
                shell.exec('echo exit 1')
            } else {
                let message = await transformer();
                let description = message.commit;
                gitPush(description)
            }
        } else {
            shell.exec('exit 1')
        }
    } else {
        log('eslint lint 通过, 请输入commit内容', 'green');
        let message = await transformer();
        let description = message.commit;
        gitPush(description)
    }
}

init()
